<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @filter-change="changeFilter" />
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id">
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <!-- 加载 -->
        <RbtInfiniteLoading
          :loading="loading"
          :finished="finished"
          @infinite="getData"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
import { ParamsType, CateGoryGoods } from '@/types/category'

const route = useRoute()
const loading = ref(false)
const finished = ref(false)
const goodsList = ref<CateGoryGoods[]>([])

// 查询参数
let reqParams: ParamsType = {
  page: 1,
  pageSize: 20
}

// 获取数据函数
const getData = () => {
  loading.value = true
  reqParams.categoryId = route.params.id as string
  findSubCategoryGoods(reqParams).then(res => {
    if (res.data.result.items.length) {
      goodsList.value.push(...res.data.result.items)
      reqParams.page++
    } else {
      // 加载完毕
      finished.value = true
    }
    loading.value = false
  })
}

// 切换二级分类重新加载
watch(
  () => route.params.id,
  newVal => {
    if (newVal && route.path === `/category/sub/${newVal}`) {
      finished.value = false
      goodsList.value = []
      reqParams = {
        page: 1,
        pageSize: 20
      }
    }
  }
)

// 监听筛选区改变
const changeFilter = (filterParams: ParamsType) => {
  finished.value = false
  reqParams = { ...reqParams, ...filterParams }
  reqParams.page = 1
  goodsList.value = []
}

// 监听排序改变
const changeSort = (sortParams: ParamsType) => {
  finished.value = false
  reqParams = { ...reqParams, ...sortParams }
  reqParams.page = 1
  goodsList.value = []
  getData()
}
</script>

<style scoped lang="scss">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
